package com.dfc.springmvc.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.dfc.springmvc.pojo.UserInfo;

@Repository
public class CommonInterceptor implements HandlerInterceptor {

	private Logger log = Logger.getLogger(this.getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");
		if (null != userInfo) {
			return true;
		} else {
			// response.sendRedirect(request.getContextPath()+"/pages/login.jsp");
			// request.getRequestDispatcher("/pages/login.jsp").forward(request,response);
			PrintWriter out = response.getWriter();
			StringBuilder builder = new StringBuilder();
			builder.append("<script type=\"text/javascript\" charset=\"utf-8\">");
			builder.append("window.top.location.href=\"");
			builder.append(request.getContextPath());
			builder.append("/pages/login.jsp");
			builder.append("\";</script>");
			out.print(builder.toString());
			out.close();
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}
}
